<template>
  <div>
    <van-search
      v-model="searchValue"
      placeholder="请输入搜索关键词"
      shape="round"
    />
    <!-- 热门搜索 -->
    <div class="search_wrap" v-if="searchResultList.length === 0">
      <p class="hot_title">热门搜索</p>
      <ul class="hot_name_wrap">
        <li
          class="hot_item"
          v-for="(obj, index) in keyWordList"
          :key="index"
          @click="btn(obj.first)"
        >
          {{ obj.first }}
        </li>
      </ul>
    </div>
    <!-- 搜索结果 -->
    <div class="search_wrap" v-else>
      <!-- 标题 -->
      <p class="hot_title">最佳匹配</p>
      <song-item
        v-for="obj in searchResultList"
        :key="obj.id"
        :name="obj.name"
        :author="obj.ar[0].name"
        :id="obj.id"
      ></song-item>
    </div>
  </div>
</template>

<script>
import { hotSearchApi, searchResultApi } from "@/api";
import SongItem from "@/components/SongItem.vue";
export default {
  components: { SongItem },
  data() {
    return {
      searchValue: "",
      keyWordList: [], //热搜关键字
      searchResultList: [], //搜索结果数据列表
      timer: null,
    };
  },
  mounted() {
    hotSearchApi().then((res) => {
      console.log(res);
      if (res.data.code === 200) {
        this.keyWordList = res.data.result.hots;
      }
    });
  },
  methods: {
    btn(val) {
      this.searchValue = val; //点击的关键字赋予给输入框显示
      searchResultApi({
        type: 1,
        keywords: this.searchValue,
      }).then((searchRes) => {
        console.log(searchRes);
        if (searchRes.data.code === 200) {
          this.searchResultList = searchRes.data.result.songs;
        }
      });
      setTimeout(() => {
        clearTimeout(this.timer);
      });
    },
  },
  watch: {
    //侦听输入框的改变
    searchValue() {
      console.log(this.searchValue);
      // 防抖
      // 防止输入框空值，还显示原来的数据，保证最后那次网络请求定时器关闭
      clearTimeout(this.timer);
      //判断输入框无值的情况
      if (this.searchValue.length === 0) {
        return (this.searchResultList = []);
      }
      this.timer = setTimeout(() => {
        searchResultApi({
          type: 1,
          keywords: this.searchValue,
        }).then((searchRes) => {
          // console.log(searchRes);
          if (searchRes.data.code === 200) {
            this.searchResultList = searchRes.data.result.songs;
          }
        });
      }, 500);
    },
  },
};
</script>

<style scoped>
div /deep/.van-field__control {
  font-size: 14px;
}
.search_wrap {
  padding: 0.266667rem;
}
/* 热门搜索标题样式 */
.hot_title {
  font-size: 0.32rem;
  color: #666;
}
/* 热搜词_容器 */
.hot_name_wrap {
  margin: 0.266667rem 0;
}

/* 热搜词_样式 */
.hot_item {
  display: inline-block;
  height: 0.853333rem;
  margin-right: 0.213333rem;
  margin-bottom: 0.213333rem;
  padding: 0 0.373333rem;
  font-size: 0.373333rem;
  line-height: 0.853333rem;
  color: #333;
  border-color: #d3d4da;
  border-radius: 0.853333rem;
  border: 1px solid #d3d4da;
}
</style>